<meta charset="UTF-8">

<?php
include_once("../functions/db_manipulate.php");
include_once("functions/utils/ImageUtil.php");

if (!init()) {
  redirect("?action=login");
}
connectDB();

$uploaddir = getcwd() . \controller\Config::getPropertyByKey('directory.user.image');

$initiatorAction = \controller\ControllerUtil::getEncodedActionFromUrlWithParameters($_SERVER['HTTP_REFERER']);

switch ($_POST['action']) {
  case 'delete':
    startTransaction();
    $prevImgResultSet = mysql_query("SELECT image FROM users WHERE id=" . $_SESSION['id']) or die(mysql_error());
    $prevPath = mysql_fetch_assoc($prevImgResultSet);
    $prevPath = $uploaddir . $prevPath['image'];
    unlink($prevPath);
    mysql_query("UPDATE users SET image='' WHERE id=" . $_SESSION['id']) or die(mysql_error());
    if ($prevImgResultSet) {
      commitTransaction();
      redirect("?action=msg&header=header.user.image.delete.success&body=body.user.image.delete.success&view=" . $initiatorAction);
    } else {
      rollbackTransaction();
      redirect("?action=msg&header=header.user.image.delete.failed&body=body.user.image.delete.failed&view=" . $initiatorAction);
    }
    break;

  case 'change':
    startTransaction();
    $prevImgResultSet = mysql_query("SELECT image FROM users WHERE id='" . $_SESSION['id'] . "'") or die(mysql_error());
    $prevPath = mysql_fetch_assoc($prevImgResultSet);
    $prevPath = $uploaddir . $prevPath['image'];
    unlink($prevPath);

    $deleteImgResultSet = mysql_query("UPDATE users SET image='' WHERE id=" . $_SESSION['id'])or die(mysql_error());

    $file = $_SESSION['id'] . "_" . date("dmY") . "_" . date("GHi") . getFormattedTime() . "_user_img" . "." . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $newImg = $uploaddir . $file;

    $addResultSet = null;

    if (move_uploaded_file($_FILES['image']['tmp_name'], $newImg)) {
      $addResultSet = mysql_query("UPDATE users SET image='" . $file . "' WHERE id='" . $_SESSION['id'] . "'")or die(mysql_error());
      \util\ImageUtil::createImagePreview($newImg, 250, 'preview/user_img_preview', 'user_img');
    }


    if ($addResultSet && $deleteImgResultSet && $prevImgResultSet) {
      commitTransaction();
      redirect("?action=msg&header=header.user.image.change.success&body=body.user.image.change.success&view=" . $initiatorAction);
    } else {
      rollbackTransaction();
      redirect("?action=msg&header=header.user.image.change.failed&body=body.user.image.change.failed&view=" . $initiatorAction);
    }
    break;
}
